package giit.computerbase.action;

import giit.computerbase.server.InitializeServer;
import giit.computerbase.util.Application;
import giit.computerbase.util.DealWithAddress;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * User: tum0r
 * Package Name: giit.computerbase.action
 * Time: 2018/11/9 Friday 23:36:23
 */
public class InitializeDatabase extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding((String) Application.getConfig().pageConfig.get("encode"));
        response.setCharacterEncoding((String) Application.getConfig().pageConfig.get("encode"));
        String toPath = "warn.jsp?";
        if (DealWithAddress.dealWith(request.getRemoteAddr()).equals("127.0.0.1")) {
            InitializeServer server = new InitializeServer();
            JSONObject jsonObject = JSONObject.fromObject(server.init(request.getHeader("user-agent")));
            if (jsonObject.getBoolean("state")) {
                toPath += "state=panel-primary&title=" + URLEncoder.encode("初始化") + "&context=" + URLEncoder.encode("初始化成功\n\n用户名：tum0r\n\n密码：") + jsonObject.getString("password") + "&preview=home.jsp";
            } else {
                toPath += "state=panel-danger&title=" + URLEncoder.encode("初始化") + "&context=" + URLEncoder.encode("初始化数据库失败，点击返回") + "&preview=index";
            }
        } else {
            toPath += "state=panel-danger&title=" + URLEncoder.encode("初始化") + "&context=" + URLEncoder.encode("初始化数据库失败，请使用服务器本机浏览器") + "&preview=index";
        }
        response.sendRedirect(toPath);
    }
}
